package com.tank.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/9/17 0017
 * Time: 下午 6:13
 * To change this template use File | Settings | File Templates.
 */
public class SocketChannelClientTest {

    public static void main(String[] args) throws Exception{

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress("10.0.50.41",8080));
        while (true) {
            selector.select();
            selector.selectedKeys().forEach(item -> {
                if(item.isConnectable()){
                    SocketChannel client =  (SocketChannel)item.channel();

                    if(client.isConnectionPending()){
                        try {
                            client.register(selector,SelectionKey.OP_READ);
                            client.finishConnect();
                            System.out.println("连接成功");
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            byteBuffer.put((System.currentTimeMillis()+":连接成功").getBytes());
                            byteBuffer.flip();
                            client.write(byteBuffer);

                            //启动线程监听键盘输入
                            ExecutorService executorService = Executors.newSingleThreadExecutor();
                            executorService.submit(()->{
                                while (true) {
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                                    try {
                                        byteBuffer.clear();
                                        String line = reader.readLine();
                                        byteBuffer.put(line.getBytes());
                                        byteBuffer.flip();
                                        client.write(byteBuffer);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                //可读事件
                }else if(item.isValid() && item.isReadable()){
                    SocketChannel client =  (SocketChannel)item.channel();
                    ByteBuffer readBuf = ByteBuffer.allocate(1024);
                    try {
                        int readLength = client.read(readBuf);
                        readBuf.flip();
                        if(readLength > 0){
                            String receivedMessage = new String(readBuf.array(),0,readLength) ;
                            System.out.println("接受消息:"+receivedMessage);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
//                        item.cancel();
//                        try {
//                            client.socket().close();
//                            client.close();
//                            return;
//                        } catch (IOException e1) {
//                            return;
//                        }

                    }
                }
                selector.selectedKeys().clear();
            });
        }
    }
}
